// Copyright 2019 The rhyme_lph Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// T [author] rhyme_lph
// L [email]  rhymelph@gmail.com
// a [github] https://github.com/rhymelph

import 'package:base_plugin/base_plugin.dart';
import 'package:finance_app/generated/a.dart';
import 'package:finance_app/generated/l10n.dart';
import 'package:finance_app/src/common/app_colors.dart';
import 'package:finance_app/src/common/app_spaces.dart';
import 'package:finance_app/src/provider/login/update_email_provider.dart';
import 'package:finance_app/src/widgets/button/normal_button.dart';
import 'package:finance_app/src/widgets/common/normal_error_text.dart';
import 'package:finance_app/src/widgets/common_app_bar.dart';
import 'package:finance_app/src/widgets/input/input_field.dart';
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:finance_app/src/router_gen/router_meta.dart';
import 'package:flutter_svg/svg.dart';
import 'package:pin_code_fields/pin_code_fields.dart';
import 'package:intl/intl.dart';

@RouterMeta(paramName: "updateEmailNumberPage")
class UpdateEmailPage extends StatefulWidget {
  @override
  _UpdateEmailPageState createState() => _UpdateEmailPageState();
}

class _UpdateEmailPageState extends State<UpdateEmailPage>
    with PagePresenter<UpdateEmailPage, UpdateEmailProvider> {
  @override
  PreferredSizeWidget get appBar => getDefaultAppBar(
        title: 'Update Email',
      );

  @override
  Widget get buildWidget => ColoredBox(
        color: Colors.white,
        child: listBuilder<int>(
            builder: (BuildContext context, int value, Widget child) =>
                IndexedStack(
                  children: [
                    _buildFirstScreen(),
                    _buildSecondScreen(),
                    _buildThirdScreen(),
                  ],
                  index: value,
                ),
            selector: (_, __) => __.step),
      );

  Widget _buildFirstScreen() => ListView(
        children: [
          AppSpaces.h40,
          _buildTipText(tip: 'Enter your email:'),
          AppSpaces.h20,
          listBuilder<bool>(
            selector: (_, __) => __.hasEmailError,
            builder: (BuildContext context, bool value, Widget child) =>
                InputField(
              focusNode: provider.emailFocus,
              controller: provider.emailController,
              hint: S.current.email,
              hasError: value,
            ),
          ),
          listBuilder<bool>(
            selector: (_, __) => __.hasEmailError,
            builder: (BuildContext context, bool value, Widget child) =>
                NormalErrorText(
              content: 'Please enter a valid email address',
              isVisibility: value,
              margin: EdgeInsets.only(
                left: getDp(45),
                top: getDp(15),
              ),
            ),
          ),
          AppSpaces.h30,
          listBuilder<bool>(
              builder: (BuildContext context, bool value, Widget child) =>
                  NormalButton(
                    title: S.current.get_otp,
                    onTap: value == true ? provider.onGetOTP : null,
                  ),
              selector: (_, __) => __.enableGetOTP),
        ],
      );

  Widget _buildSecondScreen() => ListView(
        children: [
          AppSpaces.h40,
          _buildTipText(tip: S.current.enter_your_password),
          AppSpaces.h20,
          listBuilder<bool>(
              builder: (BuildContext context, bool value, Widget child) =>
                  InputField(
                    key: ValueKey("Enter Password"),
                    leading: SvgPicture.asset(
                      A.assetsImagesCreatePadlock2,
                      width: getDp(15),
                      height: getDp(15),
                    ),
                    tip: S.current.password,
                    isPassword: true,
                    hasError: value,
                    helpText:
                        value == true ? S.current.password_is_incorrect : null,
                    controller: provider.passwordController,
                    focusNode: provider.passwordFocusNode,
                  ),
              selector: (_, __) => __.passwordError),
          AppSpaces.h30,
          listBuilder<bool>(
              builder: (BuildContext context, bool value, Widget child) =>
                  NormalButton(
                    title: S.current.verify,
                    onTap: value == true ? provider.onVerify : null,
                  ),
              selector: (_, __) => __.enableVerify),
        ],
      );

  Widget _buildThirdScreen() => ListView(
        children: [
          AppSpaces.h40,
          _buildTipText(
              tip:
                  'Please enter the 6-digit OTP sent to\nyour email: ${provider.number}'),
          AppSpaces.h20,
          Padding(
            padding: EdgeInsets.symmetric(
              horizontal: getDp(52),
            ),
            child: listBuilder<bool>(
                builder: (BuildContext context, bool value, Widget child) =>
                    PinCodeTextField(
                      key: ValueKey("Register Password"),
                      controller: provider.validateController,
                      appContext: context,
                      textStyle: TextStyle(
                        color: aceBlackColor,
                        fontSize: getSp(16),
                        fontWeight: FontWeight.w400,
                        height: 22 / 16,
                      ),
                      pastedTextStyle: TextStyle(
                        color: aceBlackColor,
                        fontSize: getSp(16),
                        fontWeight: FontWeight.w400,
                        height: 22 / 16,
                      ),
                      length: 6,
                      animationType: AnimationType.fade,
                      pinTheme: PinTheme(
                          shape: PinCodeFieldShape.underline,
                          borderWidth: getDp(1),
                          selectedColor:
                              value == true ? aceRedColor : aceBlueColor,
                          activeColor:
                              value == true ? aceRedColor : aceBlueColor,
                          inactiveColor: aceGrayColor),
                      cursorColor: aceBlueColor,
                      animationDuration: Duration(milliseconds: 300),
                      // enableActiveFill: true,
                      // errorAnimationController: errorController,
                      // controller: textEditingController,
                      keyboardType: TextInputType.number,
                      onCompleted: (v) {},
                      beforeTextPaste: (text) {
                        return true;
                      },
                      onChanged: (String value) {},
                    ),
                selector: (_, __) => __.hasValidateError),
          ),
          _buildInputValidateTip(),
          AppSpaces.h30,
          listBuilder<bool>(
              builder: (BuildContext context, bool value, Widget child) =>
                  NormalButton(
                    title: S.current.update,
                    onTap: value == true ? provider.onUpdate : null,
                  ),
              selector: (_, __) => __.enableUpdate),
          AppSpaces.h20,
          Center(
            child: Text.rich(TextSpan(
                text: S.current.no_receive_opt,
                children: [
                  TextSpan(
                      text: S.current.resend_otp,
                      style: TextStyle(
                        color: aceBlueColor,
                        fontWeight: FontWeight.bold,
                      ),
                      recognizer: TapGestureRecognizer()
                        ..onTap = provider.onResentOTP)
                ],
                style: TextStyle(
                    fontSize: getSp(14),
                    color: aceDarkGrayColor,
                    fontWeight: FontWeight.w400,
                    fontFamily: "DinRoundPro"))),
          )
        ],
      );

  Center _buildInputValidateTip() {
    return Center(
      child: listBuilder<int>(
          builder: (BuildContext context, int expire, Widget child) =>
              listBuilder<bool>(
                  builder: (BuildContext context, bool value, Widget child) =>
                      Text(
                        value == true
                            ? S.current.have_entered_the_wrong_otp
                            : expire == 0
                                ? S.current.otp_has_expired
                                : S.current.otp_expires_in_time(
                                    DateFormat('mm:ss').format(
                                        DateTime(0, 0, 0, 0, 0)
                                            .add(Duration(seconds: expire)))),
                        style: TextStyle(
                          color: value == true ? aceRedColor : aceDarkGrayColor,
                          fontSize: getSp(12),
                          fontWeight: FontWeight.w400,
                          height: 16 / 12,
                        ),
                      ),
                  selector: (_, __) => __.hasValidateError),
          selector: (_, __) => __.currentOTPExpireTimer),
    );
  }

  Widget _buildTipText({String tip}) {
    return Center(
      child: Text(
        tip,
        textAlign: TextAlign.center,
        style: TextStyle(
          color: aceBlackColor,
          fontSize: getSp(16),
          fontWeight: FontWeight.bold,
        ),
      ),
    );
  }
}
